package com.by.component.contract.support;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.by.component.aliyun.oss.OssServiceImpl;
import com.by.component.staticresources.enums.StaticResourcesTypeEnum;
import com.by.toolkit.exceptions.ServiceException;
import com.by.toolkit.platform.ByContext;
import com.by.toolkit.utils.ExceptionUtil;
import com.by.toolkit.utils.SplitterUtil;
import com.by.toolkitspring.config.AsyncExecutorConfig;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class ContractSupport {

    @Resource
    private OssServiceImpl ossService;

    @Resource
    private AsyncExecutorConfig asyncExecutorConfig;

    public Long imageToPdf(String url) {
        File uploadTmpFile = null;
        Document document = null;
        Long recourseId = null;
        try {
            document = new Document();
            String uploadTmpFilePath = FileUtil.getTmpDirPath() + File.separator + ".pdf";
            uploadTmpFile = FileUtil.file(uploadTmpFilePath);
            // 设置文档页边距
            document.setMargins(0, 0, 0, 0);
            PdfWriter.getInstance(document, new FileOutputStream(uploadTmpFile));
            // 打开文档
            document.open();
            Image image = getImage(url);
            // 设置页面宽高与图片一致
            Rectangle rectangle = new Rectangle(image.getScaledWidth(), image.getScaledHeight());
            document.setPageSize(rectangle);
            // 新建一页添加图片
            document.newPage();
            document.add(image);
            document.close();
            String fileName = SplitterUtil.EN_OBLIQUE_LINE_JOINER.join("contract", ByContext.getCorpCode(), ByContext.getProjectId(), System.currentTimeMillis() + ".pdf");
            recourseId = ossService.uploadFile2Id(StaticResourcesTypeEnum.FILE.getCode(), fileName, uploadTmpFile);
        } catch (Exception e) {
            log.error("[ContractSupport][imageToPdf] 合同图片转PDF失败:{}", ExceptionUtil.getStackTrace(e));
            throw new ServiceException("合同上传失败");
        } finally {
            if (Objects.nonNull(document)) {
                document.close();
            }
            if (Objects.nonNull(uploadTmpFile)) {
                asyncExecutorConfig.getAsyncExecutor().execute(uploadTmpFile::deleteOnExit);
            }
        }
        return recourseId;
    }

    public Long htmlToPdf(String url) {
        File uploadPdfTemFile = null;
        File downLoadHtmlTemFile = null;
        Document document = null;
        Long recourseId = null;
        try {
            document = new Document(PageSize.A4);
            // 下载html临时文件
            String downloadHtmlTmpFilePath = FileUtil.getTmpDirPath() + File.separator + IdUtil.simpleUUID() + ".html";
            downLoadHtmlTemFile = FileUtil.file(downloadHtmlTmpFilePath);
            HttpUtil.downloadFileFromUrl(url, downLoadHtmlTemFile);

            // 读取html文件中的内容
            String htmlContent = readHtmlContent(downLoadHtmlTemFile);

            // 创建pdf临时文件
            String uploadPdfTmpFilePath = FileUtil.getTmpDirPath() + File.separator + IdUtil.simpleUUID() + ".pdf";
            uploadPdfTemFile = FileUtil.file(uploadPdfTmpFilePath);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(uploadPdfTemFile));
            document.open();

            // 将html内容转换为PDF
            XMLWorkerHelper.getInstance().parseXHtml(writer,
                    document,
                    new ByteArrayInputStream(htmlContent.getBytes()),
                    Charset.forName("UTF-8"),
                    new CustomXMLWorkerFontProvider());
            document.close();

            // 上传pdf
            String fileName = SplitterUtil.EN_OBLIQUE_LINE_JOINER.join("contract", ByContext.getCorpCode(), ByContext.getProjectId(), System.currentTimeMillis() + ".pdf");
            recourseId = ossService.uploadFile2Id(StaticResourcesTypeEnum.FILE.getCode(), fileName, uploadPdfTemFile);
        } catch (Exception e) {
            log.error("[ContractSupport][htmlToPdf] 合同html转PDF失败:{}", ExceptionUtil.getStackTrace(e));
            throw new ServiceException("合同上传失败");
        } finally {
            if (Objects.nonNull(document)) {
                document.close();
            }
            if (Objects.nonNull(uploadPdfTemFile)) {
                asyncExecutorConfig.getAsyncExecutor().execute(uploadPdfTemFile::deleteOnExit);
            }
            if (Objects.nonNull(downLoadHtmlTemFile)) {
                asyncExecutorConfig.getAsyncExecutor().execute(downLoadHtmlTemFile::deleteOnExit);
            }
        }
        return recourseId;
    }

    private Image getImage(String url) throws BadElementException, IOException {
        // 获取图片的宽高
        Image image = Image.getInstance(url);
        // 调整图片缩放
        image.scaleToFit(600, 600);
        // 图片居中
        image.setAlignment(Image.ALIGN_CENTER);
        return image;
    }

    public String readHtmlContent(File downloadTmpFile) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(downloadTmpFile));
        StringBuilder htmlContent = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            htmlContent.append(line);
        }
        reader.close();
        String content = htmlContent.toString();
        content = content.replace("<br>", "<br/>")
                .replace("<uni-view", "<div").replace("</uni-view>", "</div>");
        content = regexImg(content);
//        content = HtmlUtil.unwrapHtmlTag(content, "img");
        return content;
    }

    public static String regexImg(String html) {
        String imgRegex = "<img\\s+[^>]*src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
        Pattern pattern = Pattern.compile(imgRegex);
        // 匹配img标签
        Matcher matcher = pattern.matcher(html);
        while (matcher.find()) {
            String imgStr = matcher.group();
            System.out.println(imgStr);
            html = html.replace(imgStr, imgStr + "</img>");
        }
        return html;
    }

    public static class CustomXMLWorkerFontProvider extends XMLWorkerFontProvider {
        @Override
        public Font getFont(final String fontName, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) {
            BaseFont bf;
            try {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                Font font = new Font(bf, size, style, color);
                font.setColor(color);
                return font;
            } catch (Exception e) {
                log.error("exception:", e);
            }
            return null;
        }
    }


//    private static final String DEST = "/Users/hanrongjun/Downloads/out4.pdf";
//    private static final String HTML = "https://r-t-apuwyr.gh6a.com/User/ContractTemplate/1715409967037-6hi6oa-3hurvw.html";

    /*
    public static void main(String[] args) throws IOException, DocumentException {
        Document document;
        File uploadTmpFile = null;
        try {
            document = new Document();
            String uploadTmpFilePath = "/Users/hanrongjun/Downloads/232.pdf";
            uploadTmpFile = FileUtil.file(uploadTmpFilePath);

            PdfWriter.getInstance(document, new FileOutputStream(uploadTmpFile));
            document.open();
            Image image = Image.getInstance("http://by-r-t-apuwyr.oss-cn-beijing.aliyuncs.com/contract/test/ssssss.png");
            // 调整图片缩放
            image.scaleToFit(1000, 1000);
            // 图片居中
            image.setAlignment(Image.ALIGN_CENTER);
            document.add(image);
        }catch (Exception e) {
            log.error("[ContractSupport][imageToPdf] 合同图片转PDF失败:{}", ExceptionUtil.getStackTrace(e));
            throw new ServiceException("合同上传失败");
        } finally {
            if (Objects.nonNull(document)) {
                document.close();
            }
//            if (Objects.nonNull(uploadTmpFile)) {
//                uploadTmpFile.delete();
//            }
        }
    }
*/
/*

    public static String readHtmlContentFromUrl(String url) throws IOException {
        String downloadTmpFilePath = FileUtil.getTmpDirPath() + File.separator + IdUtil.simpleUUID() + ".html";
        File downloadTmpFile = FileUtil.file(downloadTmpFilePath);
        HttpUtil.downloadFileFromUrl(url, downloadTmpFile);
        BufferedReader reader = new BufferedReader(new FileReader(downloadTmpFile));
        StringBuilder htmlContent = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            htmlContent.append(line);
        }
        reader.close();
        String content = htmlContent.toString();
        content = content.replace("<br>", "<br/>")
                .replace("<uni-view", "<div").replace("</uni-view>", "</div>");
        content = regexImg(content);
//        content = HtmlUtil.unwrapHtmlTag(content, "meta");
        return content;
    }

    // <img src="./1715395899033-qh8p74-ghj17j_files/1714476754040-jd6bbt-ixveda.png" draggable="false"></img>
    // <img src="" draggable="false">


    public static String readTextFromFile(String fileName) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        StringBuilder htmlContent = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            htmlContent.append(line);
        }
        reader.close();
        String content = htmlContent.toString();
        content = content.replace("<br>", "<br/>")
                .replace("<uni-view", "<div").replace("</uni-view>", "</div>");
//        content = HtmlUtil.unwrapHtmlTag(content, "img");
        return content;
    }

    public static void main(String[] args) throws IOException {
        String htmlContent = ContractSupport.readHtmlContentFromUrl(HTML);

//        String htmlContent = readTextFromFile("/Users/hanrongjun/Downloads/test2.html");
        System.out.println(htmlContent);
        try {
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
            document.open();
            // 将HTML内容转换为PDF
            XMLWorkerHelper.getInstance().parseXHtml(writer,
                    document,
                    new ByteArrayInputStream(htmlContent.getBytes()),
                    Charset.forName("UTF-8"),
                    new CustomXMLWorkerFontProvider());
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    */
}
